package com.chenyanqing.model.two.factory;

import com.chenyanqing.model.two.annotation.TimeLog;
import com.chenyanqing.model.two.annotation.Transactional;
import com.chenyanqing.model.two.utils.TransactionalManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class TimeLogAnnotationProxyFactory implements ProxyFactory {


    private static Logger logger = LoggerFactory.getLogger(TimeLogAnnotationProxyFactory.class);


    /**
     * 构造方法私有化
     */
    private TimeLogAnnotationProxyFactory(){

    }

    private static  TimeLogAnnotationProxyFactory factory = new TimeLogAnnotationProxyFactory();

    public static TimeLogAnnotationProxyFactory getInstance(){
        return factory;
    }

    /**
     * Object object：委托对象
     * @return  返回代理对象
     */
    public Object getJDKProxy(Object object){
        Object proxy = Proxy.newProxyInstance(object.getClass().getClassLoader(),
                object.getClass().getInterfaces(), new InvocationHandler() {
                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        TimeLog annotation = method.getAnnotation(TimeLog.class);
                        logger.info("method:{},annotation:{}",method.getName(),annotation);
                        if(annotation==null){
                            return method.invoke(object,args);
                        }else {
                            logger.info("TimeLog annotation:执行时间统计切面逻辑执行,method:{}",method);
                            //开始时间
                            Long start = System.currentTimeMillis();
                            try {
                               return method.invoke(object, args);
                            } finally {
                                //结束时间
                                Long end = System.currentTimeMillis();
                                logger.info("TimeLog annotation:日志统计：方法执行时间={}秒", (end - start) / 1000);
                                //方法执行之后的增强
                            }
                        }
                    }
                });
        logger.info("TimeLog annotation:生成事务管理代理对象后,返回值class={}",proxy.getClass().getName());
        return proxy;
    }
}
